package services

import (
	"errors"
	"time"

	"game-simple/internal/infrastructure/config"
	"github.com/golang-jwt/jwt/v5"
)

type JWTService struct {
	secret       []byte
	expiresHours int
	issuer       string
}

type Claims struct {
	UserID   uint   `json:"user_id"`
	Username string `json:"username"`
	jwt.RegisteredClaims
}

func NewJWTService() *JWTService {
	cfg := config.GetConfig()
	return &JWTService{
		secret:       []byte(cfg.JWT.Secret),
		expiresHours: cfg.JWT.ExpiresHours,
		issuer:       cfg.JWT.Issuer,
	}
}

// GenerateToken 生成 JWT token
func (s *JWTService) GenerateToken(userID uint, username string) (string, error) {
	now := time.Now()
	expiresAt := now.Add(time.Duration(s.expiresHours) * time.Hour)

	claims := Claims{
		UserID:   userID,
		Username: username,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expiresAt),
			IssuedAt:  jwt.NewNumericDate(now),
			NotBefore: jwt.NewNumericDate(now),
			Issuer:    s.issuer,
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(s.secret)
}

// ValidateToken 验证并解析 JWT token
func (s *JWTService) ValidateToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("无效的签名方法")
		}
		return s.secret, nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	}

	return nil, errors.New("无效的 token")
}

